package com.zf.yichat.controller.sys;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zf.yichat.controller.BaseController;
import com.zf.yichat.model.SysDict;
import com.zf.yichat.model.SysDictData;
import com.zf.yichat.service.SysDictService;
import com.zf.yichat.utils.response.FsPage;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

@Controller
@RequestMapping("dict")
public class DictController extends BaseController {

    @Autowired
    private SysDictService dictService;

    @RequestMapping("/index")
    public String index() {
        return "sys/dict/index";
    }

    @RequestMapping("/list")
    @ResponseBody
    public FsResponse list(Integer page, Integer limit, String name) {

        return dictService.selectIndexList(FsPage.init(page, limit), name);
    }

    @RequestMapping("save/index")
    public String saveIndex(Integer id) {
        SysDict dict = dictService.selectById(id);
        getRequest().setAttribute("dict", Objects.nonNull(id) ? dict : null);
        getRequest().setAttribute("dataList", Objects.nonNull(dict) ? dictService.selectDataByDictCode(dict.getCode()) : null);

        return "sys/dict/save";
    }

    @PostMapping("save")
    @ResponseBody
    public FsResponse save(SysDict dict, String dataList) {

        return FsResponseGen.gen(dictService.save(dict, StringUtils.isNotBlank(dataList) ? JSON.parseArray(dataList, SysDictData.class) : Lists.newArrayList()) == 1);
    }
}
